﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SPMS.Common;
using SPMS.Data;
using SPMS.Web.Models;
using SPMS.Web.Mvc;

namespace SPMS.Web.Controllers
{
    /// <summary>
    /// 账户控制器
    /// </summary>
    ///[AuthorizeEx]
    public class AccountController : Controller
    {
        #region ---Actions

        /// <summary>
        /// 用户登录。
        /// </summary>
        /// <param name="returnUrl">返回地址。</param>
        /// <returns>动作结果。</returns>
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            //设置返回的地址
            ViewBag.ReturnUrl = returnUrl;

            //返回视图
            return View();
        }

        /// <summary>
        /// 用户登录。
        /// </summary>
        /// <param name="model">登录参数。</param>
        /// <param name="returnUrl">返回地址。</param>
        /// <returns>
        /// 动作结果。
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            //判断模型是否有效
            if (ModelState.IsValid)
            {
                //执行登录
                LoginResult result = this.DoLogin(model);

                //判断是否修改登录密码
                if (result == LoginResult.ChangePassword)
                {
                    //如果需要修改密码，则重定向到修改密码画面
                    return this.RedirectToAction("ChangePassword", new { ReturnUrl = returnUrl });
                }
                else if (result == LoginResult.Successful)
                {
                    //如果登录成功，则重定向到首页
                    return this.RedirectToAction("Index", "Home");
                }
                else
                {
                    //获得错误信息
                    string errorMessage = this.GetLoginResultMessage(result);

                    //设置模型错误
                    this.ModelState.AddModelError("", errorMessage);

                    //返回视图
                    return View(model);
                }
            }

            //返回视图
            return View(model);
        }

        /// <summary>
        /// 用户登录。
        /// </summary>
        /// <param name="model">登录参数。</param>
        /// <param name="returnUrl">返回地址。</param>
        /// <returns>
        /// 动作结果。
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        public JsonResult AjaxLogin(LoginModel model)
        {
            //执行登录
            LoginResult result = this.DoLogin(model);

            //返回数据
            return this.JsonEx(true, result);
        }

        /// <summary>
        /// 注销。
        /// </summary>
        /// <returns>动作结果。</returns>
        public ActionResult Logout()
        {
            //执行登出操作
            FormsAuthentication.SignOut();

            //重定向到登录画面
            return this.RedirectToAction("Login", "Account");
        }

        /// <summary>
        /// 修改登录密码。
        /// </summary>
        /// <returns>密码修改视图。</returns>
        public ActionResult ChangePassword()
        {
            return View();
        }

        /// <summary>
        /// 账户管理。
        /// </summary>
        /// <returns>动作结果。</returns>
        [AllowAnonymous]
        public ActionResult Manage()
        {
            return View();
        }

        /// <summary>
        /// 创建账户。
        /// </summary>
        /// <param name="model">账户模型。</param>
        /// <returns>执行结果。</returns>
        [HttpPost]
        [JsonHandleError]
        ///[PermissionRequirements(new int[] { 10000001 }, new string[] { "SystemAdmin" })]
        public ActionResult Create(AccountModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名用户是否存在
                if (context.Users.Any(item => item.LoginName == model.LoginName))
                {
                    //返回结果
                    return new JsonResultEx
                    (
                        new JsonResultViewModel()
                        {
                            success = false,
                            message = string.Format("名为'{0}'的账户已经存在，账户名不允许重复。<br/>请将账户名指定为其它名称。", model.LoginName)
                        },
                        JsonRequestBehavior.AllowGet
                    );
                }

                //创建实体
                User entity = new User()
                {
                    User_ID = Guid.NewGuid(),
                    Organization_ID = model.Organization_ID,
                    Email = model.Email,
                    EmployeeName = model.EmployeeName,
                    IsAuthorized = model.IsAuthorized,
                    IsBuildin = false,
                    IsEnabled = model.IsEnabled,
                    IsLocked = false,
                    LastLoginTime = null,
                    LockedTime = null,
                    LoginName = model.LoginName,
                    Memo = model.Memo,
                    MustChangePassword = true,
                    PhoneNumber1 = model.PhoneNumber1,
                    PhoneNumber2 = model.PhoneNumber2,
                    RetryTimes = 0,
                    Seat = null,
                    Title = model.Title
                };

                //获得密码
                string password = GetDefaultPassword(entity);

                //计算密码哈希
                password = FormsAuthenticationHelper.HashPassword(password);

                //设置密码
                entity.Password = password;

                //判断是否上传了图片
                if (model.Signature_ID.HasValue)
                {
                    //获得签名图片尺寸
                    Size imageSize = this.GetSignatureImageSize();

                    //将临时文件转换为图片
                    entity.Signature = FileUploadHelper.ConvertTempFileToImage(context, model.Signature_ID.Value, imageSize.Width, imageSize.Height, 0, System.Drawing.Imaging.ImageFormat.Png, Color.Transparent);
                }

                //添加实体
                context.Users.Add(entity);

                //判断是否指定了角色
                if (model.Roles != null && model.Roles.Length > 0)
                {
                    //循环创建实体
                    foreach (Guid roleID in model.Roles)
                    {
                        //创建实体
                        UserRole item = new UserRole()
                        {
                            Role_ID = roleID,
                            User_ID = entity.User_ID
                        };

                        //添加实体
                        context.UserRoles.Add(item);
                    }
                }

                //启动事务
                using (TransactionScope transaction = new TransactionScope())
                {
                    //保存变化
                    context.SaveChanges();

                    //提交事务
                    transaction.Complete();
                }

                //判断是否上传了图片
                if (model.Signature_ID.HasValue)
                {
                    //删除临时文件
                    FileUploadHelper.DeleteTempFile(model.Signature_ID.Value);
                }

                //返回结果
                return this.JsonEx(true, entity.User_ID);
            }
        }

        /// <summary>
        /// 删除账户。
        /// </summary>
        /// <param name="model">要删除的账户。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Delete(AccountModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //判断是否内置账户
                    if (entity.IsBuildin)
                    {
                        //返回结果
                        return this.JsonEx(false, "内置账户不允许删除。");
                    }

                    //删除
                    context.Users.Remove(entity);

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 修改账户状态。
        /// </summary>
        /// <param name="model">要修改状态的账户。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [JsonHandleError]
        public ActionResult ChangeState(AccountModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //修改状态
                    entity.IsEnabled = !model.IsEnabled;

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }
                else
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在，无法更新。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 解除账户的锁定状态。
        /// </summary>
        /// <param name="model">要解锁的账户。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Unlock(AccountModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //清除锁定状态
                    entity.IsLocked = false;
                    entity.LastLoginTime = null;

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }
                else
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在，无法更新。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 重置账户的登陆密码。
        /// </summary>
        /// <param name="model">要重置密码的账户。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult ResetPassword(AccountModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //获得密码
                    string password = GetDefaultPassword(entity);

                    //计算密码哈希
                    password = FormsAuthenticationHelper.HashPassword(password);

                    //清除锁定状态
                    entity.MustChangePassword = true;
                    entity.Password = password;

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }
                else
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在，无法更新。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //返回结果
                return this.JsonEx();
            }
        }


        /// <summary>
        /// 获得账户详细信息。
        /// </summary>
        /// <param name="model">用户查询模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpGet]
        [JsonHandleError]
        public ActionResult Detail(AccountQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断是否有数据
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //用于保存地址
                string signatureUrl = null;

                //设置签名图片地址
                if (entity.Signature != null && entity.Signature.Length > 0)
                {
                    //设置地址
                    signatureUrl = string.Format("{0}?User_ID={1:B}", this.Url.Action("GetSignatureImage"), entity.User_ID);
                }

                //创建数据
                var data = new
                {
                    entity.User_ID,
                    entity.LoginName,
                    Organization = entity.Organization.Organization_Code + " " + entity.Organization.Organization_Name,
                    entity.Organization_ID,
                    entity.Organization.Organization_Code,
                    entity.Organization.Organization_Name,
                    entity.Email,
                    entity.EmployeeName,
                    entity.IsAuthorized,
                    entity.IsBuildin,
                    entity.IsEnabled,
                    entity.IsLocked,
                    entity.MustChangePassword,
                    entity.LastLoginTime,
                    entity.PhoneNumber1,
                    entity.PhoneNumber2,
                    HasSignature = (null != entity.Signature && entity.Signature.Length > 0),
                    entity.Title,
                    SignatureUrl = signatureUrl
                };

                //返回数据
                return this.JsonEx(true, data, 1);
            }
        }

        /// <summary>
        /// 获得签名图片。
        /// </summary>
        /// <param name="userID">账户查询模型。</param>
        /// <returns>签名图片反馈。</returns>
        public ActionResult GetSignatureImage(AccountQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断是否有数据
                if (null == entity && entity.Signature != null && entity.Signature.Length > 0)
                {
                    //返回结果
                    return null;
                }

                //返回文件结果
                return this.File(entity.Signature, FileUploadHelper.GetImageMIME(ImageFormat.Png), "Signature.png");
            }
        }

        /// <summary>
        /// 账户授权。
        /// </summary>
        /// <param name="model">授权模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Authorize(AuthorizeModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //用于保存角色信息
                    List<Guid> roles = new List<Guid>();

                    //判断是否指定了角色
                    if (model.Roles != null && model.Roles.Length > 0)
                    {
                        //添加角色列表
                        roles.AddRange(model.Roles);
                    }

                    //查询授权信息
                    foreach (UserRole item in context.UserRoles.Where(item => item.User_ID == model.User_ID))
                    {
                        //判断是否存在
                        if (roles.Contains(item.Role_ID))
                        {
                            //如果存在，则删除
                            roles.Remove(item.Role_ID);
                        }
                        else
                        {
                            //删除实体
                            context.UserRoles.Remove(item);
                        }
                    }

                    //循环添加实体
                    foreach (Guid roleID in roles)
                    {
                        //创建实体
                        UserRole item = new UserRole()
                        {
                            Role_ID = roleID,
                            User_ID = model.User_ID
                        };

                        //添加实体
                        context.UserRoles.Add(item);
                    }

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }
                else
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在，无法更新。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 更新账户。
        /// </summary>
        /// <param name="model">账户模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Update(AccountModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名账户是否存在
                if (context.Users.Any(item => item.LoginName == model.LoginName && item.User_ID != model.User_ID))
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户已经存在，账户名不允许重复。<br/>请将账户名指定为其它名称。", model.LoginName));
                }

                //获得账户信息
                User entity = context.Users.FirstOrDefault(item => item.User_ID == model.User_ID);

                //判断是否存在
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的账户信息不存在，无法更新。<br/>请确认此账户是否已经被删除。", model.LoginName));
                }

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //判断是否上传了图片
                    if (model.Signature_ID.HasValue)
                    {
                        //获得签名图片尺寸
                        Size imageSize = this.GetSignatureImageSize();

                        //将临时文件转换为图片
                        entity.Signature = FileUploadHelper.ConvertTempFileToImage(context, model.Signature_ID.Value, imageSize.Width, imageSize.Height, 0, System.Drawing.Imaging.ImageFormat.Png, Color.Transparent);
                    }

                    //更新实体
                    entity.Organization_ID = model.Organization_ID;
                    entity.Email = model.Email;
                    entity.EmployeeName = model.EmployeeName;
                    entity.IsAuthorized = model.IsAuthorized;
                    entity.IsEnabled = model.IsEnabled;
                    entity.LoginName = model.LoginName;
                    entity.Memo = model.Memo;
                    entity.PhoneNumber1 = model.PhoneNumber1;
                    entity.PhoneNumber2 = model.PhoneNumber2;
                    entity.Title = model.Title;

                    //用于保存角色信息
                    List<Guid> roles = new List<Guid>();

                    //判断是否指定了角色
                    if (model.Roles != null && model.Roles.Length > 0)
                    {
                        //添加角色列表
                        roles.AddRange(model.Roles);
                    }

                    //查询授权信息
                    foreach (UserRole item in context.UserRoles.Where(item => item.User_ID == model.User_ID))
                    {
                        //判断是否存在
                        if (roles.Contains(item.Role_ID))
                        {
                            //如果存在，则删除
                            roles.Remove(item.Role_ID);
                        }
                        else
                        {
                            //删除实体
                            context.UserRoles.Remove(item);
                        }
                    }

                    //循环添加实体
                    foreach (Guid roleID in roles)
                    {
                        //创建实体
                        UserRole item = new UserRole()
                        {
                            Role_ID = roleID,
                            User_ID = model.User_ID
                        };

                        //添加实体
                        context.UserRoles.Add(item);
                    }

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }

                    //判断是否上传了图片
                    if (model.Signature_ID.HasValue)
                    {
                        //删除临时文件
                        FileUploadHelper.DeleteTempFile(model.Signature_ID.Value);
                    }
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 获得账户信息列表。
        /// </summary>
        /// <param name="queryModel">查询模型对象。</param>
        /// <returns>账户信息列表。</returns>
        [HttpGet]
        [JsonHandleError]
        public JsonResult List(JsonPagingQueryModel queryModel)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //用于保存总记录数
                int totalRecord = 0;

                //创建内部查询
                var innerQuery = from item in context.Users
                                 select new
                                 {
                                     item.User_ID,
                                     item.LoginName,
                                     Organization = item.Organization.Organization_Name,
                                     item.Organization_ID,
                                     item.Organization.Organization_Code,
                                     item.Organization.Organization_Name,
                                     item.Email,
                                     item.EmployeeName,
                                     item.IsAuthorized,
                                     item.IsBuildin,
                                     item.IsEnabled,
                                     item.IsLocked,
                                     item.MustChangePassword,
                                     item.LastLoginTime,
                                     item.Memo,
                                     item.PhoneNumber1,
                                     item.PhoneNumber2,
                                     HasSignature = (null != item.Signature),
                                     item.Title
                                 };
                //查询数据
                var query = innerQuery.QueryData(queryModel, out totalRecord);

                //获得数据
                var data = query.ToArray();

                //返回数据
                return new JsonResultEx
                (
                    new JsonResultViewModel()
                    {
                        success = true,
                        data = data,
                        total = totalRecord
                    },
                    JsonRequestBehavior.AllowGet
                );
            }
        }

        /// <summary>
        /// 获得用户角色信息列表。
        /// </summary>
        /// <param name="userID">用户编号。</param>
        /// <returns>
        /// 账户信息列表。
        /// </returns>
        [HttpGet]
        [JsonHandleError]
        public JsonResult UserRoles(Guid userID)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询用户信息
                User user = context.Users.FirstOrDefault(item => item.User_ID == userID);

                //判断用户是否存在
                if (null == user)
                {
                    //直接返回
                    return this.JsonEx();
                }

                //创建查询
                var query = from role in context.Roles.Include("Users")
                            join tempItem in context.UserRoles.Where(item => item.User_ID == userID) on role.Role_ID equals tempItem.Role_ID into temp
                            from user_role in temp.DefaultIfEmpty()
                            select new
                            {
                                role.Role_ID,
                                role.Role_Title,
                                role.Role_Name,
                                role.Role_Desc,
                                IsAssigned = (null != user_role)
                            };

                //获得数据
                var data = query.ToArray();

                //返回结果
                return this.JsonEx(true, data, data.Length);
            }
        }

        #endregion

        #region ---Private Method

        /// <summary>
        /// 获得签名图片尺寸。
        /// </summary>
        /// <value>
        /// 签名图片尺寸。
        /// </value>
        private Size GetSignatureImageSize()
        {
            return new Size(192, 128);
        }

        /// <summary>
        /// 获得指定用户默认密码。
        /// </summary>
        /// <param name="entity">用户实体。</param>
        /// <returns>
        /// 指定用户的默认密码。
        /// </returns>
        private string GetDefaultPassword(User entity)
        {
            //返回默认密码
            return SystemSettings.GetDefaultPassword(entity);
        }

        /// <summary>
        /// 执行登录。
        /// </summary>
        /// <param name="model">登录模型。</param>
        /// <returns>是否成功登录。</returns>
        private LoginResult DoLogin(LoginModel model)
        {
            //判断用户名或者密码是否为空
            if (string.IsNullOrEmpty(model.LoginName) || string.IsNullOrEmpty(model.Password))
            {
                //返回结果
                return LoginResult.Failed;
            }

            //用于保存返回结果
            LoginResult result = LoginResult.Failed;

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //检索用户信息
                User entity = context.Users.FirstOrDefault(item => item.LoginName == model.LoginName);

                //判断用户信息是否存在
                if (null != entity)
                {
                    //判断密码是否有效
                    if (FormsAuthenticationHelper.IsPasswordEqual(model.Password, entity.Password))
                    {
                        if (!entity.IsEnabled)
                        {
                            //判断是否禁用
                            //设置结果
                            result = LoginResult.Forbidden;
                        }
                        else if (entity.RetryTimes > SystemSettings.Login_RetryTimes)
                        {
                            //判断是否超过重试次数
                            //设置锁定
                            entity.IsLocked = true;
                            entity.LockedTime = DateTime.Now;
                            entity.RetryTimes = 0;

                            //设置结果
                            result = LoginResult.Locked;
                        }
                        else if (entity.IsLocked)
                        {
                            //判断账号是否被锁定
                            //获得锁定时间
                            DateTime lockedTime = DateTime.Now;

                            //判断锁定时间是否有效
                            if (entity.LockedTime.HasValue)
                            {
                                //获得锁定时间
                                lockedTime = entity.LockedTime.Value;
                            }
                            else
                            {
                                //设置锁定时间
                                entity.LockedTime = lockedTime;
                            }

                            //判断是否已经可以解锁
                            if (DateTime.Now.Subtract(lockedTime) >= SystemSettings.Login_LockTimeout)
                            {
                                //清除锁定状态
                                entity.IsLocked = false;
                                entity.LockedTime = null;
                                entity.RetryTimes = 0;

                                //设置结果
                                result = LoginResult.Successful;
                            }
                            else
                            {
                                //设置结果
                                result = LoginResult.Locked;
                            }
                        }
                        else
                        {
                            //设置最后登录时间
                            entity.LastLoginTime = DateTime.Now;

                            //创建会话
                            Session newSession = new Data.Session()
                            {
                                Session_ID = Guid.NewGuid(),
                                User_ID = entity.User_ID,
                                CreateTime = DateTime.Now
                            };

                            //添加会话
                            context.Sessions.Add(newSession);

                            //创建窗体认证凭据
                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, entity.User_ID.ToString("B"), DateTime.Now, DateTime.Now.Add(SystemSettings.Session_Timeout), model.RememberMe, newSession.Session_ID.ToString("B"));

                            //创建Cookie
                            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

                            //添加Cookie
                            this.HttpContext.Response.Cookies.Add(cookie);

                            //判断是否需要修改密码
                            if (entity.MustChangePassword)
                            {
                                //设置结果
                                result = LoginResult.ChangePassword;
                            }
                            else
                            {
                                //设置结果
                                result = LoginResult.Successful;
                            }
                        }
                    }
                    else
                    {
                        //增加重试次数
                        entity.RetryTimes += 1;
                    }

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }

                //返回结果
                return result;
            }
        }

        /// <summary>
        /// 重定向到指定的地址。
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        private ActionResult LocalRedirect(string returnUrl)
        {
            //判断是否指定了重定向地址
            if (Url.IsLocalUrl(returnUrl))
            {
                //重定向
                return LocalRedirect(returnUrl);
            }
            else
            {
                //重定向到首页
                return RedirectToAction("Index", "Home");
            }
        }

        /// <summary>
        /// 获得登录结果返回消息。
        /// </summary>
        /// <param name="result">登录结果。</param>
        /// <returns>返回消息。</returns>
        private string GetLoginResultMessage(LoginResult result)
        {
            switch (result)
            {
                case LoginResult.Failed:
                    return SPMS.Web.Properties.Resources.text_error_login_failed;
                case LoginResult.Forbidden:
                    return SPMS.Web.Properties.Resources.text_error_login_account_forbidden;
                case LoginResult.Locked:
                    return SPMS.Web.Properties.Resources.text_error_login_account_locked;
                case LoginResult.Successful:
                    return string.Empty;
                case LoginResult.ChangePassword:
                    return SPMS.Web.Properties.Resources.text_msg_changepassword;
                default:
                    return string.Empty;
            }
        }

        #endregion
    }
}
